/**
 * Created by jianglinjie on Wed Sep 27 2017
 * @flow
 */
'use strict';

import type { RegisterParam, RegisterResult } from '../types';
import type { IRegisterStrategy } from './IRegisterStrategy';
import { ErrorCode } from '../../../constants';
import { RegisterType } from '../../../constants';
import { createError } from '../../../utils/ErrorUtils';
import User from '../../../db/models/User';
import { md5 } from '../../../utils/StringUtils';
import { isPhone } from '../../../utils/CheckUtils';
import { getCaptchaRedisKey } from '../../../utils/CaptchaUtils';
import { CaptchaBusiness } from '../../../constants';
import redis from '../../../redis';
import { logger } from '../../../utils/LoggerUtils';
import { isMongoDuplicateKeyError } from '../../../utils/ErrorUtils';
import { checkPass } from '../../../utils/CheckUtils';

export default class PhonePwdCaptchaStrategy implements IRegisterStrategy {
  async register(param: RegisterParam): Promise<RegisterResult> {
    if (!isPhone(param.phone)) {
      throw createError(400, '手机号不合法', ErrorCode.PHONE_INVALID);
    }

    if (!checkPass(param.pwd)) {
      throw createError(400, '密码非法', ErrorCode.PASSWORD_INVALID);    
    }

    if (!param.captcha) {
      throw createError(400, '缺少验证码', ErrorCode.REQUIRE_CAPTCHA);    
    }

    //获取缓存的验证码
    let redisKey = getCaptchaRedisKey(param.phone, CaptchaBusiness.REGISTER);
    let captcha = await redis.getAsync(redisKey);

    if (captcha !== param.captcha) {
      throw createError(400, '验证码失效，请重新获取验证码', ErrorCode.CAPTCHA_INVALID);
    }
    //注册成功 删除验证码
    redis.delAsync(redisKey).catch(delErr => {
      logger.error('redis delAsync redisKey:%s error ', redisKey, delErr);
    });

    try {
      //newUser叫文档
      let newUser = await User.create({
        registerType: RegisterType.PHONE_PWD_CAPTCHA,
        phone: param.phone,
        pwd: param.pwd,
        encryptPwd: md5(param.pwd),
        gender: param.gender,
        avatar: param.avatar,
        nickName: param.nickName,
      });

      return newUser.toUserInfo();      
    } catch (err) {
      if (isMongoDuplicateKeyError(err)) {
        throw createError(409, '手机号已注册', ErrorCode.USER_HAS_REGISTER);        
      } else {
        throw err;
      }
    }
  }  
}